package com.sdp.irrigation.controller;


import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.irrigation.db.irrigation_notice.service.IIrrigationNoticeService;
import com.sdp.irrigation.entity.IrrigationNotice;
import com.sdp.irrigation.utils.CurrentLoginEmp;

/**
 * <p>
 * 公告 前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-12-31
 */
@RestController
@RequestMapping("/IrrigationNoticeController")
public class IrrigationNoticeController {

	@Autowired
	private Query query;
	
	@Autowired
	private IIrrigationNoticeService iIrrigationNoticeService;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private CurrentLoginEmp currentLoginEmp;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iIrrigationNoticeService, IrrigationNotice.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody IrrigationNotice noticeInfo) {
		if(noticeInfo==null) {
			return Result.error("公告息为空");
		}
		
		noticeInfo.setUpdateTime(LocalDateTime.now());
		
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		noticeInfo.setOpName(emp.getString("empName"));
		noticeInfo.setOpNo(emp.getString("empNo"));
		
		if(StringUtils.isEmpty(noticeInfo.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iIrrigationNoticeService, IrrigationNotice.class, new String[] {"noticeTitle"}, "keyId", noticeInfo, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("标题不能重复");
			}
			noticeInfo.setCreateTime(LocalDateTime.now());
			iIrrigationNoticeService.save(noticeInfo);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iIrrigationNoticeService, IrrigationNotice.class, new String[] {"noticeTitle"}, "keyId", null, noticeInfo, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("标题不能重复");
			}
			iIrrigationNoticeService.updateById(noticeInfo);
		}
		
		return Result.ok();
	}
}

